package org.seanye.erp.view.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    private static final String YYYY_MM_DD = "yyyy-MM-dd";
    private static final SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);

    public static String format(Date date) {
	return sdf.format(date);
    }

    public static Date parse(String str) throws Exception {
	try {
	    return sdf.parse(str);
	} catch (Exception e) {
	    throw new Exception(str + " is not a valid date.");
	}
    }

    public static Date getFirstDayOfWeek(String str) throws Exception {
	Date date = parse(str);
	return isFirstDayOfWeek(str, date);
    }

    public static Date isFirstDayOfWeek(String str, Date date) throws Exception {
	Calendar instance = Calendar.getInstance();
	instance.setTime(date);
	int firstDayOfWeek = instance.get(Calendar.DAY_OF_WEEK);
	if (firstDayOfWeek == 2) {
	    return date;
	} else
	    throw new Exception(str + " is not first day of week.");
    }

    public static Date nextWeek(Date now) {
	Calendar instance = Calendar.getInstance();
	instance.setTime(now);
	instance.add(Calendar.DAY_OF_YEAR, 7);
	return instance.getTime();
    }

    public static Date privWeek(Date now) {
	Calendar instance = Calendar.getInstance();
	instance.setTime(now);
	instance.add(Calendar.DAY_OF_YEAR, -7);
	return instance.getTime();
    }
}
